<template>
  <div class="app-container">
    <!-- 筛选区域 -->
    <div class="filter-container">
      <el-form :inline="true" class="demo-form-inline"  >
        <el-form-item label="文章类型：">
          <el-select 
            v-model="filterForm.category" 
            placeholder="请选择类型" 
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="文章标题：">
          <el-input 
            v-model="filterForm.title" 
            placeholder="请输入标题" 
            clearable 
            style="width: 200px"
          />
        </el-form-item>
      
        <el-form-item label="发布时间：">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 310px;"
            @change="handleDateChange"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button size="small" @click="resetForm">重置</el-button>
          <el-button size="small" type="primary" @click="handleSearch">搜索</el-button>
          
          <el-button size="small" type="primary" @click="addNews">添加</el-button>
        </el-form-item>
      
      </el-form>
    </div>
    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px;"
    >
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="title" label="标题" min-width="200" />
      <el-table-column prop="author" label="作者" width="120" align="center" />
      <el-table-column prop="summary" label="摘要" min-width="180" />
      <!-- <el-table-column prop="content" label="内容" min-width="180" /> -->
      <el-table-column prop="createDate" label="创建时间" width="160" />
      <el-table-column prop="modifyDate" label="修改时间" width="160" />
      <el-table-column prop="name" label="类型" width="100">
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-link type="primary" @click="handleView(row)">查看</el-link>
          <el-divider direction="vertical" />
          <el-link type="danger" @click="handleDelete(row)">删除</el-link>
          <el-divider direction="vertical" />
          <el-link type="success" @click="handleEdit(row)">修改</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 详情弹窗 -->
    <el-dialog
      title="新闻详情"
      v-model="dialogVisible"
      width="50%"
    >
      <div class="detail-content">
        <h3>{{ newsDetail.title }}</h3>
        <div class="meta-info">
          <span>作者：{{ newsDetail.author }}</span>
          <span style="margin-left: 20px">分类：{{ newsDetail.name }}</span>
        </div>
        <div class="time-info">
          <span>创建时间：{{ newsDetail.createDate }}</span>
          <span style="margin-left: 20px">修改时间：{{ newsDetail.modifyDate }}</span>
        </div>
        <el-divider />
        <div class="summary">
          <h4>新闻摘要</h4>
          <p>{{ newsDetail.summary }}</p>
        </div>
        <div class="summary">
          <h4>新闻内容</h4>
          <p>{{ newsDetail.content }}</p>
        </div>
    
      </div>
    </el-dialog>

    <!-- 分页组件 -->
    <el-pagination
      class="pagination-container"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :background="true"
      layout="total, sizes, prev, pager, next"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>
<script>export default {
  data() {
    return {
      dialogVisible: false,
      newsDetail: {},
      filterForm: {
        category: null,
        title: '',
        dateRange: [],
      },
      categoryOptions: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      newsList:[],
      tableData: [],
    }
  },
  created() {
    this.fetchNewsData() // 初始化数据
  },
  methods: {
    // 日期选择事件
    handleDateChange(val) {
      console.log('时间范围数据：', {
        start: val ? val[0] : null,
        end: val ? val[1] : null
      });
    },
    
    //查询数据
    fetchNewsData(){
      this.$axios.get('/news/list', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          categoryId: this.filterForm.category,
          title: this.filterForm.title,
          ...(this.filterForm.dateRange && this.filterForm.dateRange.length === 2 && {
            beginDate: this.filterForm.dateRange[0],
            endDate: this.filterForm.dateRange[1]
          })
        }
      }).then(res => {
      this.tableData = res.data.data.allNews.list;
          this.total = res.data.data.allNews.total;
          this.categoryOptions = res.data.data.newsCategory.map(item => ({
            value: item.id,
            label: item.name
          }));
          
      })
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize
      this.fetchNewsData()
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage
      this.fetchNewsData()
    },
    
    handleSearch() {
      this.currentPage = 1
      this.fetchNewsData()
    },
    resetForm() {
      this.filterForm = {
        category: '',
        title: '',
        dateRange: [],
      };
    },
    // 查看详情
    async handleView(row) {
      try {
        const { data } = await this.$axios.get(`/news/list/${row.id}`)
        this.newsDetail = data.data
        this.dialogVisible = true
      } catch (error) {
        this.$message.error('获取详情失败：' + error.message)
      }
    },
    // 编辑操作
    handleEdit(row) {
      console.log('编辑：', row);
      this.$router.push(`/apinews/edit/${row.id}`);
    },
    // 删除操作
    handleDelete(row) {
      this.$axios.post(`/news/delete/${row.id}`).then(res => {
        if (res.data.code !== 200) {
          this.$message.error('删除用户失败');
          return;
        }
        //加点弹窗让用户是否删除提示
        this.$confirm('确定要删除该用户吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
            .then(() => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.fetchNewsData()
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              })
            })
      }).catch(error => {
        console.error('删除用户失败:', error);
      })
  },
  // 添加新闻
  addNews() {
    this.$router.push('/apinews/add');
  }
}
}
</script>
<style scoped>
.filter-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
  display: flex;
  justify-content: center;
}
.detail-content {
  padding: 0 20px;
}
.meta-info {
  color: #666;
  margin: 15px 0;
}
.time-info {
  color: #999;
  font-size: 12px;
  margin-bottom: 15px;
}
.summary h4 {
  color: #333;
  margin-bottom: 10px;
}
.summary p {
  line-height: 1.6;
  color: #666;
}

</style>